/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package org.netbeans.modules.web.click.wizards;

import java.awt.Component;
import java.awt.Dimension;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import java.util.List;
import javax.lang.model.element.TypeElement;
import javax.swing.ComboBoxModel;
import javax.swing.DefaultComboBoxModel;
import javax.swing.DefaultListCellRenderer;
import javax.swing.Icon;
import javax.swing.JList;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
import javax.swing.event.DocumentListener;
import org.netbeans.api.java.source.ClasspathInfo;
import org.netbeans.api.java.source.ElementHandle;
import org.netbeans.api.java.source.ui.TypeElementFinder;
import org.netbeans.api.project.Project;
import org.netbeans.api.project.ProjectUtils;
import org.netbeans.api.project.SourceGroup;
import org.netbeans.api.project.Sources;
import org.netbeans.modules.web.api.webmodule.WebModule;
import org.netbeans.modules.web.api.webmodule.WebProjectConstants;
import org.netbeans.modules.web.click.editor.ClickEditorUtilities;
import org.netbeans.spi.java.project.support.ui.PackageView;
import org.openide.filesystems.FileObject;
import org.openide.filesystems.FileUtil;
import org.openide.util.NbBundle;
import org.openide.util.Parameters;
import org.openide.util.RequestProcessor;

public final class ClickPageVisualPanel1 extends JPanel implements ActionListener, DocumentListener {

    /** Creates new form ClickPageVisualPanel1 */
    public ClickPageVisualPanel1() {
        initComponents();
    }
    private Project project;
    private SourceGroup[] groups;
    private final List<ChangeListener> listeners = new ArrayList<ChangeListener>();

    public ClickPageVisualPanel1(Project project, SourceGroup[] groups) {
        Parameters.notNull("Project can not be null", project);
        Parameters.notNull("groups can not be null", groups);

        this.project = project;
        this.groups = groups;
        initComponents();
        textClassName.getDocument().addDocumentListener(this);
        cmbSourceFolder.addActionListener(this);
        cmbPackage.getEditor().addActionListener(this);
        cmbPackage.addActionListener(this);
        textSuperClass.getDocument().addDocumentListener(this);
        textTemplateFileName.getDocument().addDocumentListener(this);
        textWebFolder.getDocument().addDocumentListener(this);

        cmbSourceFolder.setRenderer(new GroupListCellRenderer());
        cmbPackage.setRenderer(PackageView.listRenderer());
    }

    @Override
    public String getName() {
        return "Create Click Page";
    }
    private static final Dimension PREF_DIM = new Dimension(500, 340);

    @Override
    public void addNotify() {
        Dimension panel2Size = this.getPreferredSize();

        int vmax = panel2Size.height + 12;   //Insets=12
        //Update only height, keep the wizard width
        if (vmax > PREF_DIM.height) {
            this.setPreferredSize(new Dimension(PREF_DIM.width, vmax));
        }
        super.addNotify();
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        lbProject = new javax.swing.JLabel();
        textProject = new javax.swing.JTextField();
        htmlPanel = new javax.swing.JPanel();
        cbxTemplateFile = new javax.swing.JCheckBox();
        jLabel6 = new javax.swing.JLabel();
        textTemplateFileName = new javax.swing.JTextField();
        lbWebFolder = new javax.swing.JLabel();
        textWebFolder = new javax.swing.JTextField();
        btBrowseWebFolder = new javax.swing.JButton();
        clsPanel = new javax.swing.JPanel();
        jLabel2 = new javax.swing.JLabel();
        textClassName = new javax.swing.JTextField();
        cmbSourceFolder = new javax.swing.JComboBox();
        jLabel3 = new javax.swing.JLabel();
        jLabel4 = new javax.swing.JLabel();
        cmbPackage = new javax.swing.JComboBox();
        jLabel5 = new javax.swing.JLabel();
        textSuperClass = new javax.swing.JTextField();
        btBrowseSuperClass = new javax.swing.JButton();
        cmbTemplates = new javax.swing.JComboBox();
        jLabel1 = new javax.swing.JLabel();
        cbxAddMapping = new javax.swing.JCheckBox();

        setMinimumSize(PREF_DIM);

        org.openide.awt.Mnemonics.setLocalizedText(lbProject, org.openide.util.NbBundle.getMessage(ClickPageVisualPanel1.class, "ClickPageVisualPanel1.lbProject.text")); // NOI18N

        textProject.setEditable(false);

        htmlPanel.setBorder(javax.swing.BorderFactory.createTitledBorder(org.openide.util.NbBundle.getMessage(ClickPageVisualPanel1.class, "ClickPageVisualPanel1.htmlPanel.border.title"))); // NOI18N

        cbxTemplateFile.setSelected(true);
        org.openide.awt.Mnemonics.setLocalizedText(cbxTemplateFile, org.openide.util.NbBundle.getMessage(ClickPageVisualPanel1.class, "ClickPageVisualPanel1.cbxTemplateFile.text")); // NOI18N
        cbxTemplateFile.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                cbxTemplateFileActionPerformed(evt);
            }
        });

        org.openide.awt.Mnemonics.setLocalizedText(jLabel6, org.openide.util.NbBundle.getMessage(ClickPageVisualPanel1.class, "ClickPageVisualPanel1.jLabel6.text")); // NOI18N

        org.openide.awt.Mnemonics.setLocalizedText(lbWebFolder, org.openide.util.NbBundle.getMessage(ClickPageVisualPanel1.class, "ClickPageVisualPanel1.lbWebFolder.text")); // NOI18N

        textWebFolder.setText(org.openide.util.NbBundle.getMessage(ClickPageVisualPanel1.class, "ClickPageVisualPanel1.textWebFolder.text")); // NOI18N

        org.openide.awt.Mnemonics.setLocalizedText(btBrowseWebFolder, org.openide.util.NbBundle.getMessage(ClickPageVisualPanel1.class, "ClickPageVisualPanel1.btBrowseWebFolder.text")); // NOI18N
        btBrowseWebFolder.setPreferredSize(new java.awt.Dimension(80, 21));
        btBrowseWebFolder.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btBrowseWebFolderActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout htmlPanelLayout = new javax.swing.GroupLayout(htmlPanel);
        htmlPanel.setLayout(htmlPanelLayout);
        htmlPanelLayout.setHorizontalGroup(
            htmlPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(htmlPanelLayout.createSequentialGroup()
                .addContainerGap()
                .addGroup(htmlPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(cbxTemplateFile)
                    .addGroup(htmlPanelLayout.createSequentialGroup()
                        .addGroup(htmlPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jLabel6)
                            .addComponent(lbWebFolder))
                        .addGap(26, 26, 26)
                        .addGroup(htmlPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(textWebFolder, javax.swing.GroupLayout.DEFAULT_SIZE, 241, Short.MAX_VALUE)
                            .addComponent(textTemplateFileName, javax.swing.GroupLayout.DEFAULT_SIZE, 241, Short.MAX_VALUE))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(btBrowseWebFolder, javax.swing.GroupLayout.DEFAULT_SIZE, 90, Short.MAX_VALUE)))
                .addContainerGap())
        );
        htmlPanelLayout.setVerticalGroup(
            htmlPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(htmlPanelLayout.createSequentialGroup()
                .addComponent(cbxTemplateFile)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(htmlPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel6)
                    .addComponent(textTemplateFileName, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(htmlPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(lbWebFolder)
                    .addComponent(textWebFolder, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(btBrowseWebFolder, javax.swing.GroupLayout.PREFERRED_SIZE, 21, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        clsPanel.setBorder(javax.swing.BorderFactory.createTitledBorder(org.openide.util.NbBundle.getMessage(ClickPageVisualPanel1.class, "ClickPageVisualPanel1.clsPanel.border.title"))); // NOI18N

        org.openide.awt.Mnemonics.setLocalizedText(jLabel2, org.openide.util.NbBundle.getMessage(ClickPageVisualPanel1.class, "ClickPageVisualPanel1.jLabel2.text")); // NOI18N

        textClassName.addFocusListener(new java.awt.event.FocusAdapter() {
            public void focusLost(java.awt.event.FocusEvent evt) {
                textClassNameFocusLost(evt);
            }
        });

        org.openide.awt.Mnemonics.setLocalizedText(jLabel3, org.openide.util.NbBundle.getMessage(ClickPageVisualPanel1.class, "ClickPageVisualPanel1.jLabel3.text")); // NOI18N

        org.openide.awt.Mnemonics.setLocalizedText(jLabel4, org.openide.util.NbBundle.getMessage(ClickPageVisualPanel1.class, "ClickPageVisualPanel1.jLabel4.text")); // NOI18N

        cmbPackage.setEditable(true);

        org.openide.awt.Mnemonics.setLocalizedText(jLabel5, org.openide.util.NbBundle.getMessage(ClickPageVisualPanel1.class, "ClickPageVisualPanel1.jLabel5.text")); // NOI18N

        textSuperClass.setText("org.apache.click.Page");

        org.openide.awt.Mnemonics.setLocalizedText(btBrowseSuperClass, org.openide.util.NbBundle.getMessage(ClickPageVisualPanel1.class, "ClickPageVisualPanel1.btBrowseSuperClass.text")); // NOI18N
        btBrowseSuperClass.setPreferredSize(new java.awt.Dimension(80, 21));
        btBrowseSuperClass.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btBrowseSuperClassActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout clsPanelLayout = new javax.swing.GroupLayout(clsPanel);
        clsPanel.setLayout(clsPanelLayout);
        clsPanelLayout.setHorizontalGroup(
            clsPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(clsPanelLayout.createSequentialGroup()
                .addContainerGap()
                .addGroup(clsPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jLabel3)
                    .addComponent(jLabel2)
                    .addComponent(jLabel4)
                    .addComponent(jLabel5))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(clsPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(clsPanelLayout.createSequentialGroup()
                        .addComponent(textSuperClass, javax.swing.GroupLayout.PREFERRED_SIZE, 240, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(btBrowseSuperClass, javax.swing.GroupLayout.DEFAULT_SIZE, 90, Short.MAX_VALUE))
                    .addComponent(cmbPackage, javax.swing.GroupLayout.PREFERRED_SIZE, 240, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(textClassName, javax.swing.GroupLayout.PREFERRED_SIZE, 240, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(cmbSourceFolder, javax.swing.GroupLayout.PREFERRED_SIZE, 150, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addContainerGap())
        );
        clsPanelLayout.setVerticalGroup(
            clsPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(clsPanelLayout.createSequentialGroup()
                .addGroup(clsPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel2)
                    .addComponent(textClassName, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(clsPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel3)
                    .addComponent(cmbSourceFolder, javax.swing.GroupLayout.PREFERRED_SIZE, 21, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(clsPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel4)
                    .addComponent(cmbPackage, javax.swing.GroupLayout.PREFERRED_SIZE, 21, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(clsPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel5)
                    .addComponent(textSuperClass, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(btBrowseSuperClass, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addContainerGap())
        );

        org.openide.awt.Mnemonics.setLocalizedText(jLabel1, org.openide.util.NbBundle.getMessage(ClickPageVisualPanel1.class, "ClickPageVisualPanel1.jLabel1.text")); // NOI18N

        org.openide.awt.Mnemonics.setLocalizedText(cbxAddMapping, org.openide.util.NbBundle.getMessage(ClickPageVisualPanel1.class, "ClickPageVisualPanel1.cbxAddMapping.text")); // NOI18N

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
        this.setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(clsPanel, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(htmlPanel, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addGroup(javax.swing.GroupLayout.Alignment.LEADING, layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jLabel1)
                            .addComponent(lbProject))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(cmbTemplates, javax.swing.GroupLayout.PREFERRED_SIZE, 120, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(textProject, javax.swing.GroupLayout.PREFERRED_SIZE, 320, javax.swing.GroupLayout.PREFERRED_SIZE)))
                    .addComponent(cbxAddMapping, javax.swing.GroupLayout.Alignment.LEADING))
                .addContainerGap())
        );

        layout.linkSize(javax.swing.SwingConstants.HORIZONTAL, new java.awt.Component[] {clsPanel, htmlPanel});

        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(lbProject)
                    .addComponent(textProject, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(cmbTemplates, javax.swing.GroupLayout.PREFERRED_SIZE, 21, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel1))
                .addGap(12, 12, 12)
                .addComponent(clsPanel, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(htmlPanel, javax.swing.GroupLayout.DEFAULT_SIZE, 105, Short.MAX_VALUE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(cbxAddMapping))
        );
    }// </editor-fold>//GEN-END:initComponents

    private void cbxTemplateFileActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cbxTemplateFileActionPerformed
        if (!cbxTemplateFile.isSelected()) {
            textTemplateFileName.setEditable(false);
            textWebFolder.setEnabled(false);
            btBrowseWebFolder.setEnabled(false);
            cbxAddMapping.setEnabled(false);
        } else {
            textTemplateFileName.setEditable(true);
            textWebFolder.setEnabled(true);
            btBrowseWebFolder.setEnabled(true);
            cbxAddMapping.setEnabled(true);
        }
    }//GEN-LAST:event_cbxTemplateFileActionPerformed

    private void btBrowseWebFolderActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btBrowseWebFolderActionPerformed

        Sources sources = ProjectUtils.getSources(this.project);
        org.netbeans.api.project.SourceGroup[] webGroups = sources.getSourceGroups(WebProjectConstants.TYPE_DOC_ROOT);
        org.openide.filesystems.FileObject fo = BrowseFolders.showDialog(webGroups, false);
        if (fo != null) {
            FileObject webRoot = WebModule.getWebModule(project.getProjectDirectory()).getDocumentBase();
            String relativePath = "";
            if (webRoot != null && fo != null && FileUtil.isParentOf(webRoot, fo)) {
                relativePath = FileUtil.getRelativePath(webRoot, fo);
            }
            textWebFolder.setText(relativePath);
        }

    }//GEN-LAST:event_btBrowseWebFolderActionPerformed

    private void textClassNameFocusLost(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_textClassNameFocusLost
        updateText();
    }//GEN-LAST:event_textClassNameFocusLost

    private void btBrowseSuperClassActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btBrowseSuperClassActionPerformed

        ElementHandle<TypeElement> type = TypeElementFinder.find(ClasspathInfo.create(this.getRootFolder()), null);

        if (type != null) {
            textSuperClass.setText(type.getQualifiedName());
        }

    }//GEN-LAST:event_btBrowseSuperClassActionPerformed
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btBrowseSuperClass;
    private javax.swing.JButton btBrowseWebFolder;
    private javax.swing.JCheckBox cbxAddMapping;
    private javax.swing.JCheckBox cbxTemplateFile;
    private javax.swing.JPanel clsPanel;
    private javax.swing.JComboBox cmbPackage;
    private javax.swing.JComboBox cmbSourceFolder;
    private javax.swing.JComboBox cmbTemplates;
    private javax.swing.JPanel htmlPanel;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JLabel jLabel6;
    private javax.swing.JLabel lbProject;
    private javax.swing.JLabel lbWebFolder;
    private javax.swing.JTextField textClassName;
    private javax.swing.JTextField textProject;
    private javax.swing.JTextField textSuperClass;
    private javax.swing.JTextField textTemplateFileName;
    private javax.swing.JTextField textWebFolder;
    // End of variables declaration//GEN-END:variables

    public void initValues(FileObject preselectedFolder) {
        assert project != null : "Project must be specified."; // NOI18N
        // Show name of the project
        textProject.setText(ProjectUtils.getInformation(project).getDisplayName());
        cmbTemplates.setModel(new DefaultComboBoxModel(new String[]{"Blank", "Simple Form"}));

        // Setup comboboxes
        cmbSourceFolder.setModel(new DefaultComboBoxModel(groups));
        SourceGroup preselectedGroup = getPreselectedGroup(preselectedFolder);

        cmbSourceFolder.setSelectedItem(preselectedGroup);

        Object preselectedPackage = getPreselectedPackage(preselectedGroup, preselectedFolder);

        if (preselectedPackage != null) {
            // packageComboBox.setSelectedItem( preselectedPackage );
            cmbPackage.getEditor().setItem(preselectedPackage);
        }

        updatePackages();

        //updateText();

    }

    public FileObject getRootFolder() {
        final Object selectedItem = cmbSourceFolder.getSelectedItem();
        return (selectedItem instanceof SourceGroup) ? ((SourceGroup) selectedItem).getRootFolder() : null;
    }

    public String getPackageFileName() {

        String packageName = cmbPackage.getEditor().getItem().toString();
        return packageName.replace('.', '/'); // NOI18N
    }

    /**
     * Name of selected package, or "" for default package.
     */
    public String getPackageName() {
        return cmbPackage.getEditor().getItem().toString();
    }

    public String getTemplateType() {
        return cmbTemplates.getSelectedItem().toString();
    }

    public String getPageClassName() {
        return textClassName.getText();
    }

    public String getPageClassSuperClassName() {
        return textSuperClass.getText();
    }

    public String getTemplateFileName() {
        return textTemplateFileName.getText();
    }

    public String getTemplateFilePath() {
        String fileName = textTemplateFileName.getText() == null ? "" : textTemplateFileName.getText().trim();
        String folderName = textWebFolder.getText() == null ? "" : textWebFolder.getText().trim();
        if (folderName.length() > 0) {

            if (!folderName.endsWith("/")) {
                folderName += "/";
            }
            return folderName + fileName;
        }
        return fileName;
    }

    public String getWebFolder() {
        return textWebFolder.getText();
    }

    public boolean requireCreateTemplateFile() {
        return cbxTemplateFile.isSelected();
    }

    public boolean requireAddMappingToClickXML() {
        return cbxAddMapping.isSelected();
    }

    public void addChangeListener(ChangeListener l) {
        listeners.add(l);
    }

    public void removeChangeListener(ChangeListener l) {
        listeners.remove(l);
    }

    private void fireChange() {
        ChangeEvent e = new ChangeEvent(this);
        for (ChangeListener l : listeners) {
            l.stateChanged(e);
        }
    }

    // ActionListener implementation -------------------------------------------
    public void actionPerformed(java.awt.event.ActionEvent e) {
        if (cmbSourceFolder == e.getSource()) {
            updatePackages();
            fireChange();
        } else if (cmbPackage == e.getSource()) {
            // updateText();
            fireChange();
        } else if (cmbPackage.getEditor() == e.getSource()) {
            //updateText();
            fireChange();
        } else if (textClassName == e.getSource()) {
            fireChange();
        }
    }

    // DocumentListener implementation -----------------------------------------
    public void changedUpdate(javax.swing.event.DocumentEvent e) {
        fireChange();
    }

    public void insertUpdate(javax.swing.event.DocumentEvent e) {
        changedUpdate(e);
    }

    public void removeUpdate(javax.swing.event.DocumentEvent e) {
        changedUpdate(e);
    }
    // Private methods ---------------------------------------------------------
    private RequestProcessor.Task updatePackagesTask = null;
    private static final ComboBoxModel WAIT_MODEL = new DefaultComboBoxModel(
            new String[]{
                NbBundle.getMessage(ClickPageVisualPanel1.class, "LBL_ClickPageVisualPanel1_PleaseWait") // NOI18N
            });

    private void updatePackages() {
        WAIT_MODEL.setSelectedItem(cmbPackage.getEditor().getItem());
        cmbPackage.setModel(WAIT_MODEL);

        if (updatePackagesTask != null) {
            updatePackagesTask.cancel();
        }

        updatePackagesTask = new RequestProcessor("ComboUpdatePackages").post(
                new Runnable() {

                    private ComboBoxModel model;

                    public void run() {
                        if (!SwingUtilities.isEventDispatchThread()) {
                            model = PackageView.createListView((SourceGroup) cmbSourceFolder.getSelectedItem());
                            SwingUtilities.invokeLater(this);
                        } else {
                            model.setSelectedItem(cmbPackage.getEditor().getItem());
                            cmbPackage.setModel(model);
                        }
                    }
                });

    }

//    private void updateText() {
//        final Object selectedItem =  rootComboBox.getSelectedItem();
//        String createdFileName;
//        if (selectedItem instanceof SourceGroup) {
//            SourceGroup g = (SourceGroup) selectedItem;
//            FileObject rootFolder = g.getRootFolder();
//            String packageName = getPackageFileName();
//            String documentName = documentNameTextField.getText().trim();
//            if ( type == NewJavaFileWizardIterator.TYPE_PACKAGE ) {
//                documentName = documentName.replace( '.', '/' ); // NOI18N
//            }
//            else if ( documentName.length() > 0 ) {
//                documentName = documentName + expectedExtension;
//            }
//            createdFileName = FileUtil.getFileDisplayName( rootFolder ) +
//                ( packageName.startsWith("/") || packageName.startsWith( File.separator ) ? "" : "/" ) + // NOI18N
//                packageName +
//                ( packageName.endsWith("/") || packageName.endsWith( File.separator ) || packageName.length() == 0 ? "" : "/" ) + // NOI18N
//                documentName;
//        } else {
//            //May be null iff nothing selected
//            createdFileName = "";   //NOI18N
//        }
//        fileTextField.setText( createdFileName.replace( '/', File.separatorChar ) ); // NOI18N
//    }
    private SourceGroup getPreselectedGroup(FileObject folder) {
        for (int i = 0; folder != null && i < groups.length; i++) {
            FileObject root = groups[i].getRootFolder();
            if (root.equals(folder) || FileUtil.isParentOf(root, folder)) {
                return groups[i];
            }
        }
        return groups[0];
    }

    /**
     * Get a package combo model item for the package the user selected before opening the wizard.
     * May return null if it cannot find it; or a String instance if there is a well-defined
     * package but it is not listed among the packages shown in the list model.
     */
    private Object getPreselectedPackage(SourceGroup group, FileObject folder) {
        if (folder == null) {
            return null;
        }
        FileObject root = group.getRootFolder();

        String relPath = FileUtil.getRelativePath(root, folder);

        if (relPath == null) {
            // Group Root folder is no a parent of the preselected folder
            // No package should be selected
            return null;
        } else {
            // Find the right item.
            String name = relPath.replace('/', '.');
            /*
            int max = model.getSize();
            for (int i = 0; i < max; i++) {
            Object item = model.getElementAt(i);
            if (item.toString().equals(name)) {
            return item;
            }
            }
             */
            // Didn't find it.
            // #49954: should nonetheless show something in the combo box.
            return name;
        }
    }

    private void updateText() {
        //do not compute the page name unless it is enabled.
        if (!cbxTemplateFile.isSelected()) {
            return;
        }

        if (null == getTemplateFileName() || "".equals(getTemplateFileName().trim())) {
            String classname = getPageClassName();
            String targetFileName = "";
            if (classname != null && !"".equals(classname.trim())) {
                if (classname.endsWith("Page")) {
                    classname = classname.substring(0, classname.lastIndexOf("Page"));
                }
                targetFileName = ClickEditorUtilities.convertClassNameToPathName(classname);
                textTemplateFileName.setText(targetFileName);
            }
        }
    }

    private static final class GroupListCellRenderer extends DefaultListCellRenderer {

        public GroupListCellRenderer() {
        }

        @Override
        public Component getListCellRendererComponent(JList list, Object value, int index, boolean isSelected, boolean cellHasFocus) {
            String name;
            Icon icon;
            if (value == null) {
                name = ""; //NOI18N
                icon = null;
            } else {
                assert value instanceof SourceGroup;
                SourceGroup g = (SourceGroup) value;
                name = g.getDisplayName();
                icon = g.getIcon(false);
            }
            super.getListCellRendererComponent(list, name, index, isSelected, cellHasFocus);
            setIcon(icon);
            return this;
        }
    }
}

